/** 4. 对齐相同搜索条件 */
<template>
  <div class="same_div">
    <a-row style="width: 100%" :gutter="24">
      <a-col :span="12">
        <h3>基准站点搜索条件</h3>
        <a-table
          :dataSource="step_data.same_conditions"
          :columns="tb_columns.same_condition_columns"
          :rowClassName="
            (record, index) => {
              return record.pick_me ? 'merged_row' : '';
            }
          "
          :pagination="{ pageSize: 5 }"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operation'">
              <span>
                <a class="opt_text_2" @click="load_condition_group(record)"
                  >对齐</a
                >
              </span>
            </template>
            <template v-if="column.key === 'matches_txt'">
              <span>
                {{
                  record.matches
                    .map(i => `${i.site_code}:${i.condition_name}`)
                    .join(';\n')
                }}
              </span>
            </template>
            <template v-if="column.key === 'status'">
              <ACheckCircleFilled
                style="color: green"
                v-if="record.status === true"
              />
              <ACloseCircleFilled style="color: red" v-else />
            </template>
          </template>
        </a-table>
      </a-col>
      <a-col :span="12" class="site_card_window">
        <h3 class="site_card_header">选择对齐站点</h3>
        <div class="site_card_container">
          <div
            v-bind:key="item.category_code"
            v-for="item in current_condition_group.matches.filter(
              i => !i.baseline
            )"
            :class="[
              'site_card',
              item.baseline ? 'side_card_base' : '',
              item.pick_me ? 'side_card_pick' : '',
            ]"
            @click="select_site(item)"
          >
            <a-badge-ribbon text="基准站点" color="red" v-if="item.baseline">
              <a-card size="small" hoverable class="site_card">
                <template #cover>
                  <img
                    alt="site_logo"
                    :src="item.site_logo_url"
                    style="height: 100px; object-fit: contain"
                  />
                </template>
                <h3>{{ item.category_name }}</h3>
                <p>{{ item.category_path }}</p>
                <span style="color: #999">{{ item.category_code }}</span>
              </a-card>
            </a-badge-ribbon>
            <a-card size="small" hoverable class="site_card" v-else>
              <template #cover>
                <img
                  alt="site_logo"
                  :src="item.site_logo_url"
                  style="height: 100px; object-fit: contain"
                />
              </template>
              <h3>{{ item.category_name }}</h3>
              <p>{{ item.category_path }}</p>
              <span style="color: #999">{{ item.category_code }}</span>
            </a-card>
          </div>
        </div>
      </a-col>
    </a-row>

    <a-row :gutter="20" style="margin-top: 20px">
      <a-col :span="6">
        <h3
          style="text-align: center; margin-bottom: 10px"
          v-if="base_option_data.matches?.length"
        >
          {{ base_option_data.matches[0].site_name }} >
          {{ base_option_data.matches[0].category_name }} >
          {{ base_option_data.condition_name }}
        </h3>
        <h3 style="margin-bottom: 10px" v-else>请选择对齐选项</h3>
        <a-table
          :dataSource="
            base_option_data.matches.length > 0
              ? base_option_data.matches[0].options
              : []
          "
          :columns="tb_columns.base_option_columns"
          :rowClassName="
            (record, index) => {
              return record.pick_me ? 'merged_row' : '';
            }
          "
          :pagination="{ pageSize: 10 }"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operation'">
              <span>
                <a-space direction="vertical">
                  <a-popconfirm
                    title="选择合并选项"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="merge_condition(record)"
                    @open-change="
                      event => {
                        if (!event) {
                          clear_to_merge_options();
                        }
                      }
                    "
                  >
                    <template #description>
                      <p style="margin: 10px 4px">
                        正在合并
                        {{
                          `${current_condition_group.condition_name}: ${record.option_name}`
                        }}
                        选项
                      </p>
                      <a-space direction="vertical">
                        <a-select
                          placeholder="请选择合并的选项"
                          v-model:value="to_merge_options"
                          mode="multiple"
                          style="width: 320px; margin-bottom: 12px"
                          :dropdownStyle="{ zIndex: 9999 }"
                          :options="to_merge_selector_options"
                        >
                        </a-select>
                        <a-input
                          placeholder="合并后选项名"
                          v-model:value="to_merge_option_name"
                          style="width: 320px; margin-bottom: 12px"
                        />
                      </a-space>
                    </template>
                    <a
                      class="opt_text_3"
                      key="to_same"
                      @click="gen_to_merge_options(record)"
                    >
                      {{ '合并>' }}
                    </a>
                  </a-popconfirm>
                  <!-- <a @click="pick2merge(matches[0], record)">{{ "合并>" }}</a> -->
                  <a class="opt_text_3" @click="move2merged(record)">{{
                    '右移>'
                  }}</a>
                </a-space>
              </span>
            </template>
          </template>
        </a-table>
      </a-col>
      <a-col :span="12">
        <h3 style="text-align: center; margin-bottom: 10px">合并后选项表</h3>
        <a-table
          :dataSource="current_condition_group.merged_options"
          :columns="tb_columns.merged_option_columns"
          :pagination="{ pageSize: 10 }"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operation'">
              <span>
                <a class="opt_text_2" @click="delete_merged_option(record)"
                  >删除</a
                >
              </span>
            </template>
            <template v-if="column.key == 'match_options_text'">
              <div style="line-height: 26px">
                <a-tag
                  v-for="item in record.option_matches.map(
                    i => `${i.site_code}:${i.option_name}`
                  )"
                  color="orange"
                  >{{ item }}</a-tag
                >
              </div>
              <!-- <span>
                {{
                  record.option_matches
                    .map((i) => `${i.site_code}:${i.option_name}`)
                    .join(";")
                }}
              </span> -->
            </template>
          </template>
        </a-table>
      </a-col>
      <a-col :span="6">
        <h3
          style="text-align: center; margin-bottom: 10px"
          v-if="source_option_data.condition_name"
        >
          {{ source_option_data.site_name }} >
          {{ source_option_data.category_name }} >
          {{ source_option_data.condition_name }}
        </h3>
        <h3 style="margin-bottom: 10px" v-else>请选择对齐选项</h3>
        <a-table
          :dataSource="source_option_data.options"
          :columns="tb_columns.source_option_columns"
          :rowClassName="
            (record, index) => {
              return record.pick_me ? 'merged_row' : '';
            }
          "
          :pagination="{ pageSize: 10 }"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operation'">
              <span>
                <a-space direction="vertical">
                  <a-popconfirm
                    title="选择合并选项"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="merge_condition(record)"
                    @open-change="
                      event => {
                        if (!event) {
                          clear_to_merge_options();
                        }
                      }
                    "
                  >
                    <template #description>
                      <p style="margin: 10px 4px">
                        正在合并
                        {{
                          `${current_condition_group.condition_name}: ${record.option_name}`
                        }}
                        选项
                      </p>
                      <a-space direction="vertical">
                        <a-select
                          placeholder="请选择合并的选项"
                          v-model:value="to_merge_options"
                          mode="multiple"
                          style="width: 320px; margin-bottom: 12px"
                          :dropdownStyle="{ zIndex: 9999 }"
                          :options="to_merge_selector_options"
                        >
                        </a-select>
                        <a-input
                          placeholder="合并后选项名"
                          v-model:value="to_merge_option_name"
                          style="width: 320px; margin-bottom: 12px"
                        />
                      </a-space>
                    </template>
                    <a
                      class="opt_text_3"
                      key="to_same"
                      @click="gen_to_merge_options(record)"
                      >{{ '<合并' }}</a
                    >
                  </a-popconfirm>
                  <!-- <a
                    :style="{ color: record.pick_me ? 'red' : '' }"
                    @click="pick2merge(matches[1], record)"
                    >{{ "< 合并" }}</a
                  > -->
                  <a class="opt_text_3" @click="move2merged(record)">{{
                    '<左移'
                  }}</a>
                </a-space>
              </span>
            </template>
          </template>
        </a-table>
      </a-col>
    </a-row>

    <a-space
      :style="{ width: '100%', display: 'flex', justifyContent: 'center' }"
    >
      <a-button @click="finish" type="primary">提交保存</a-button>
      <!-- <a-button @click="clear_all_condition">清空重选</a-button> -->
    </a-space>

    <read-only-mask :enabled="step_data.read_only" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import {
  fetch_process_data,
  update_step_data,
  get_site_data,
  get_process_step_data,
  clone_condition_map_by_class,
  get_condition_map,
  get_raw_condition_map,
  get_baseline_site_code,
} from '@/utils/selection';

const emit = defineEmits(['finish']);

// 获取当前进度数据
const process_data = ref({});

// 站点列表
const site_list = ref([]);

// 步骤数据
const step_data = ref({
  read_only: false,
  same_conditions: [],
});

// 当前条件选项可对齐的站点列表
const current_condition_group = ref({
  matches: [], // 当前条件选项下可对齐的站点列表
});

// 基准站点信息
const base_option_data = ref({
  options: [],
  matches: [],
});

// 源站点信息
const source_option_data = ref({});

// 加载条件组 (点击对齐按钮触发)
const load_condition_group = record => {
  console.log('do align ->', record);
  current_condition_group.value = record;

  // 将基准站点移到 matches 中的第一个
  let baseline_index = record.matches.findIndex(i => i.baseline);
  if (baseline_index !== -1) {
    let baseline_site = record.matches.splice(baseline_index, 1);
    record.matches.unshift(baseline_site[0]);
  } else {
    message.error('基准站点不存在');
    return;
  }
  // 检查是否有多个基准站点
  let baseline_count = record.matches.filter(i => i.baseline).length;
  if (baseline_count > 1) {
    message.error('存在多个基准站点');
    return;
  }

  base_option_data.value = record;
  current_condition_group.value.merged_options = record.merged_options;
  select_site(record.matches[1]); // 默认选择非基准站点的第一个站点

  // 更新选项状态
  step_data.value.same_conditions.forEach(item => {
    item.pick_me = false;
  });
  record.pick_me = true;
};

// 选择站点
const select_site = site => {
  console.log('select site ->', site);
  if (site.baseline) {
    message.warning('基准站点不能被选中');
    return;
  }
  current_condition_group.value.matches =
    current_condition_group.value.matches.map(i => {
      if (i.site_code === site.site_code) {
        i.pick_me = true;
      } else {
        i.pick_me = false;
      }
      return i;
    });
  source_option_data.value = site;
};

// 从已合并列表中检查选项是否存在
const check_option_merged = (option, merged_arr) => {
  console.log('check_option_merged ->', option, merged_arr);
  function check_exist(_option) {
    for (let i = 0; i < merged_arr.length; i++) {
      if (
        merged_arr[i].option_matches.findIndex(
          _i =>
            `${_i.site_code}:${_i.option_name}` ===
            `${_option.site_code}:${_option.option_name}`
        ) !== -1
      ) {
        return true;
      }
    }
    return false;
  }
  if (Array.isArray(option)) {
    for (let i = 0; i < option.length; i++) {
      if (check_exist(option[i])) {
        return true;
      }
    }
    return false;
  } else {
    return check_exist(option);
  }
};

// 移动到合并选项表 (点击 左移/右移 时触发)
const move2merged = record => {
  console.log('do move ->', record);
  console.log(
    'current_condition_group.value ->',
    current_condition_group.value
  );

  // 补充 option 对应的 condition_code 字段 // TODO 逻辑有误 暂时移除
  // let site_code = record.site_code;
  // let site = current_condition_group.value.matches.find(
  //   (i) => i.site_code === site_code
  // );
  // record.condition_code = site.condition_code;

  let to_merge_item = {
    key: `${record.site_code}:${record.option_name}`,
    option_name: record.option_name,
    option_value: record.option_value,
    option_value_operation: '=',
    option_matches: [record],
  };
  if (
    // 检查是否已合并的选项
    check_option_merged(
      to_merge_item.option_matches,
      current_condition_group.value.merged_options
    )
  ) {
    message.warning('已存在相同的匹配项');
    return;
  }
  // 勾选的选项置为已合并
  record.pick_me = true;
  current_condition_group.value.merged_options.push(to_merge_item);
  update_condition_status(current_condition_group.value);
};

// 已选择的待合并选项
const to_merge_selector_options = ref([]);
const to_merge_options = ref([]);
const to_merge_option_name = ref('');

// 执行选项合并
const merge_condition = record => {
  console.log('do merge ->', record);
  console.log('to_merge_options ->', to_merge_options.value);
  if (record.pick_me) {
    message.warning('当前选项已合并');
    return;
  }
  if (to_merge_options.value.length === 0) {
    message.warning('请选择需要合并的选项');
    return;
  }
  if (to_merge_option_name.value === '') {
    message.warning('请输入合并后的选项名');
    return;
  }
  function get_option_by_value(value) {
    // 通过 value 获取原选项
    let [site_code, category_code, option_name] = value.split(':');
    let site = current_condition_group.value.matches.find(
      i => i.site_code === site_code && i.category_code === category_code
    );
    console.log(`output->site`, site);
    let option = site.options.find(i => i.option_name === option_name);
    // TODO option_matches 补充 option 对应的 condition_code 字段
    option.condition_code = site.condition_code;
    return option;
  }
  // 补充 option 对应的 condition_code 字段
  record.condition_code = current_condition_group.value.condition_code;
  let to_merge_item = {
    key: `${record.site_code}:${to_merge_option_name.value}`,
    option_name: to_merge_option_name.value,
    option_value: record.option_value,
    option_value_operation: '=',
    option_matches: [
      record,
      ...to_merge_options.value.map(v => get_option_by_value(v)),
    ],
  };
  // TODO option_matches 补充 option 对应的 category_code 和 condition_code 字段
  // to_merge_item.option_matches.forEach((i) => {
  //   console.log(`output->i, site_list.value`,i, site_list.value)
  //   i.category_code = site_list.value.find((site) => {
  //     return site.site_code === i.site_code;
  //   }).category_code;
  // });

  console.log('to_merge_item ->', to_merge_item);
  // TODO 检查合并选项中必须包含基准站点
  const baseline_site_code = get_baseline_site_code(process_data.value);
  if (
    to_merge_item.option_matches.findIndex(
      i => i.site_code === baseline_site_code
    ) === -1
  ) {
    message.warning('合并选项中必须包含基准站点');
    return;
  }
  // 检查是否已合并的选项
  if (
    check_option_merged(
      to_merge_item.option_matches,
      current_condition_group.value.merged_options
    )
  ) {
    message.warning('已存在相同的匹配项');
    return;
  }
  // 勾选的选项置为已合并
  to_merge_item.option_matches.forEach(i => {
    i.pick_me = true;
  });
  current_condition_group.value.merged_options.push(to_merge_item);
  clear_to_merge_options();
  update_condition_status(current_condition_group.value);
};

// 更新选中对齐类目完成状态
const update_condition_status = condition_group => {
  let condition_done = true;
  condition_group.matches.forEach(site_condition => {
    site_condition.options.forEach(option => {
      if (!option.pick_me) {
        condition_done = false;
      }
    });
  });
  condition_group.status = condition_done;
  console.log('do update_condition_status -> condition_group', condition_group);
};

// 更新当前选中所有对齐类目的所有选项选中状态
const update_condition_check_status = condition_group => {
  condition_group.matches.forEach(site_condition => {
    site_condition.options.forEach(option => {
      option.pick_me = check_option_merged(
        option,
        condition_group.merged_options
      );
    });
  });
};

// 清空合并选项
const clear_to_merge_options = () => {
  to_merge_options.value = [];
  to_merge_option_name.value = '';
};

// 生成可合并的选项列表
const gen_to_merge_options = record => {
  console.log('gen_to_merge_options ->', record);
  let options = [];
  current_condition_group.value.matches.forEach(item => {
    console.log(`output->item`, item);
    item.options.forEach(i => {
      if (
        item.site_code !== record.site_code && // 过滤掉当前站点
        item.category_code !== record.category_code && // 过滤掉当前分类
        !i.pick_me
      ) {
        options.push({
          value: `${item.site_code}:${item.category_code}:${i.option_name}`,
          label: `${item.site_code}:${item.category_code}:${i.option_name}`,
          // value: i.option_name,
        });
      }
    });
  });
  console.log('gen options ->', options);
  to_merge_selector_options.value = options;
  to_merge_option_name.value = record.option_name;
  return options;
};

// 删除合并后的选项
const delete_merged_option = record => {
  console.log('do delete ->', record);
  // 取消勾选的选项
  record.option_matches.forEach(i => {
    i.pick_me = false;
  });
  // 从合并列表中删除
  current_condition_group.value.merged_options =
    current_condition_group.value.merged_options.filter(
      i => i.key !== record.key
    );
  update_condition_check_status(current_condition_group.value);
  update_condition_status(current_condition_group.value);
};

// 初始化: 获取当前步骤数据
onMounted(async () => {
  process_data.value = await fetch_process_data();

  // 读取当前步骤数据
  const last_step_data =
    get_process_step_data(process_data.value, 'CONFLICT_SOLVE')?.data ?? null;
  if (last_step_data) {
    step_data.value = last_step_data;
    message.success('读取过程数据成功');

    // 默认选中第一个条件组
    if (step_data.value.same_conditions.length > 0) {
      load_condition_group(step_data.value.same_conditions[0]);
    }
    return;
  }

  // 读取站点列表
  site_list.value = get_site_data(process_data.value);

  // 读取相同组的分类搜索条件映射表
  const temp_same_groups = clone_condition_map_by_class(
    process_data.value,
    'same_group'
  );

  // 补充映射表字段
  for (let group of temp_same_groups) {
    // 创建合并后选项列表
    group.merged_options = [];
    // // 补充源站点类目编码
    // group.src_category_code = site_list.value.find((site) => {
    //   return (
    //     site.site_code === group.site_code &&
    //     site.category_code === group.matches[0]
    //   );
    // }).category_code;
  }

  step_data.value.same_conditions = temp_same_groups;

  // 更新搜索条件组完成状态
  step_data.value.same_conditions.forEach(item => {
    update_condition_check_status(item);
    update_condition_status(item);
  });

  // 默认选中第一个条件组
  if (step_data.value.same_conditions.length > 0) {
    load_condition_group(step_data.value.same_conditions[0]);
  }

  console.log('step_data.value ->', step_data.value);
});

// 完成步骤: 更新提交当前步骤数据
const finish = async () => {
  message.info('正在提交数据，请稍后...');
  // 设置只读
  step_data.value.read_only = true;
  // 更新提交当前步骤数据
  if (
    await update_step_data(
      'CONFLICT_SOLVE',
      process_data.value,
      step_data.value
    )
  ) {
    // 跳转到下一步
    emit('finish');
  }
};

// 表格列配置
const tb_columns = ref({
  same_condition_columns: [
    {
      title: '站点码',
      dataIndex: 'site_code',
      key: 'site_code',
    },
    {
      title: '条件/码',
      dataIndex: 'condition_name',
      key: 'condition_name',
    },
    {
      title: '匹配条件(站码)',
      dataIndex: 'matches_txt',
      key: 'matches_txt',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
    },
  ],
  base_option_columns: [
    {
      title: '选项名',
      dataIndex: 'option_name',
      key: 'option_name',
    },
    {
      title: '选项值',
      dataIndex: 'option_value',
      key: 'option_value',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
    },
  ],
  merged_option_columns: [
    {
      title: '选项名称',
      dataIndex: 'option_name',
      key: 'option_name',
    },
    {
      title: '选项值',
      dataIndex: 'option_value',
      key: 'option_value',
    },
    // {
    //   title: "原始编码",
    //   dataIndex: "option_origin_code",
    //   key: "option_origin_code",
    // },
    // {
    //   title: "值比较符号",
    //   dataIndex: "option_value_operation",
    //   key: "option_value_operation",
    // },
    {
      title: '匹配选项 (站码)',
      dataIndex: 'match_options_text',
      key: 'match_options_text',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
    },
  ],
  source_option_columns: [
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
    },
    {
      title: '选项值',
      dataIndex: 'option_value',
      key: 'option_value',
    },
    {
      title: '选项名',
      dataIndex: 'option_name',
      key: 'option_name',
    },
  ],
});
</script>

<script>
import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons-vue';
import {
  Card,
  List,
  ListItem,
  ListItemMeta,
  Row,
  Col,
  Button,
  Space,
  Input,
  Select,
  Popconfirm,
  Table,
  BadgeRibbon,
  Tag,
} from 'ant-design-vue';
import ReadOnlyMask from '../commons/ReadOnlyMask.vue';
export default {
  components: {
    ACard: Card,
    AList: List,
    ARow: Row,
    ACol: Col,
    AListItem: ListItem,
    AListItemMeta: ListItemMeta,
    AButton: Button,
    ASpace: Space,
    ATable: Table,
    ABadgeRibbon: BadgeRibbon,
    AInput: Input,
    ASelect: Select,
    APopconfirm: Popconfirm,
    ATag: Tag,
    ACheckCircleFilled: CheckCircleFilled,
    ACloseCircleFilled: CloseCircleFilled,
  },
};
</script>

<style lang="scss">
.same_div {
  padding: 10px 100px;

  .site_card_window {
    overflow-x: scroll;
    background-color: #3331;
    border-radius: 8px;
    padding: 8px;
    position: relative;

    .site_card_header {
      position: sticky;
      top: 0;
      left: 0;
    }

    .site_card_container {
      display: flex;
      flex-direction: row;

      .site_card {
        width: 192px;
        margin-right: 20px;
        border-radius: 8px;
      }

      .side_card_base {
        border: 1px solid red;
      }

      .side_card_pick {
        border: 1px solid green;
      }
    }
  }

  .opt_text_2 {
    display: block;
    width: 40px;
  }
  .opt_text_3 {
    display: block;
    width: 60px;
  }

  .merged_row {
    background-color: rgba(255, 166, 0, 0.125);

    .ant-table-cell-row-hover {
      background-color: rgba(255, 166, 0, 0.25);
    }
  }
}
</style>
